package cn.com.blackboard.DataModule4B2.BBDataUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import blackboard.data.course.Course;
import blackboard.data.course.CourseMembership;
import blackboard.persist.DataType;
import blackboard.persist.Id;
import blackboard.persist.PersistenceException;
import blackboard.persist.course.CourseDbLoader;
import blackboard.persist.course.CourseMembershipDbLoader;
import blackboard.persist.user.UserDbLoader;
import blackboard.platform.gradebook2.BookData;
import blackboard.platform.gradebook2.BookDataRequest;
import blackboard.platform.gradebook2.GradableItem;
import blackboard.platform.gradebook2.GradeWithAttemptScore;
import blackboard.platform.gradebook2.GradebookManager;
import blackboard.platform.gradebook2.GradebookManagerFactory;
import cm.com.blackboard.DataModule4B2.customizeConfigUtils.CreditMapPropertiesUtil;
import cn.com.blackboard.DataModule4B2.model.CreditResult;

public class GradeExportUtil {

	private static final Logger logger = LoggerFactory.getLogger(GradeExportUtil.class);
	
	public static String getDbRowNameByliName(String liName){
		return CreditMapPropertiesUtil.getKeyByValue(liName);
	}
	
	public static List<CreditResult> getResult(String course_id){
		GradebookManager gbMgr = GradebookManagerFactory.getInstance();
		List<CreditResult> lstCreditResult = new ArrayList<CreditResult>();
        BookData bookData = null;
        Id courseId = null;
		try {
			courseId = Id.generateId(new DataType(Course.class), course_id);
		} catch (PersistenceException e1) {
			logger.info("course can't be find with "+course_id+" when loading credit result");
		}
        
		List<CourseMembership>cmLst = new ArrayList<CourseMembership>();
		
		try {
			cmLst = CourseMembershipDbLoader.Default.getInstance().loadByCourseId(courseId);
		} catch (Exception e1) {
			logger.info("course_enrollment can't be find with "+course_id+" when loading credit result");
		} 
		
        try {
            BookDataRequest req = new BookDataRequest(Id.generateId(new DataType(Course.class), course_id));
            bookData = gbMgr.getBookData(req);           
            List<GradeWithAttemptScore> list = bookData.getGradeWithAttemptScore();

            int rowNum = cmLst.size();
            int colNum = 0;
            if(rowNum != 0)
            	colNum = list.size()/rowNum;
            for(int i = 0; i < rowNum; i++){
            	CreditResult cr = new CreditResult();
            	CourseMembership cm = cmLst.get(i);
            	String userid = UserDbLoader.Default.getInstance().loadById(cm.getUserId()).getUserName();
                String courseid = CourseDbLoader.Default.getInstance().loadById(cm.getCourseId()).getCourseId();

                Date today = Calendar.getInstance().getTime();
                cr.setDtcreated(today);
            	cr.setUserId(userid);
            	cr.setCourseId(courseid);
            	cr.setIsExported("Y");
            	for(int j = 0; j < colNum; j++){
            		int attemptInx = i + j * rowNum; 
            		GradeWithAttemptScore attempt = list.get(attemptInx);
            		GradableItem gradeItem = GradebookManagerFactory.getGradableItemManager().getGradebookItem(attempt.getGradableItemId());
                    String scoreName = gradeItem.getDisplayColumnName();                  
    				String DbRowName = getDbRowNameByliName(scoreName);
    				String score = attempt.getTextValue();
    				
    				Method[] methods = CreditResult.class.getDeclaredMethods();
    				
    				String setMethodName = "set" + DbRowName;
    				for (int k = 0; k < methods.length; k++) { 
                        if (methods[k].getName().equalsIgnoreCase(setMethodName)) { 
                            setMethodName = methods[k].getName(); 
                            String inputvalue = score;
                            Method setMethod;
    						try {
    							setMethod = cr.getClass().getMethod( 
    							        setMethodName, inputvalue.getClass());
    	                        setMethod.invoke(cr, inputvalue); 
    						} catch (Exception e) {
    							logger.info("DbRow mapping lineitem error, please check the config file or change it from config page");
    							e.printStackTrace();
    						} 
                        }
    				}
    				
            	}
            	lstCreditResult.add(cr);     	
            }     
        }catch (Exception e){
        	logger.info("error when loading gradebook");
        }
        return lstCreditResult;
	}
	
	public static void main(String[] args) {
		String DbRowName = getDbRowNameByliName("总计");
		logger.info(DbRowName);
		
	}
}
